'use client'

import { useState, useEffect } from 'react'
import { Plus, Search, Filter, MoreHorizontal, Edit, Trash2, UserCheck, UserX, Mail, Phone, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { 
  DropdownMenu, 
  DropdownMenuContent, 
  DropdownMenuItem, 
  DropdownMenuTrigger 
} from '@/components/ui/dropdown-menu'
import { usersAPI } from '@/lib/api'
import { toast } from 'sonner'
import { AddUserDialog } from '@/components/AddUserDialog'
import { 
  CompactLayout, 
  CompactHeading, 
  CompactSubheading,
  CompactGrid,
  CompactCard 
} from '@/components/ui/compact-layout'

interface User {
  id: string
  username: string
  email: string
  role: 'ADMIN' | 'EDITOR' | 'VIEWER'
  status: 'ACTIVE' | 'INACTIVE' | 'BANNED'
  avatar?: string
  lastLoginAt?: string
  createdAt: string
  updatedAt: string
  _count: {
    knowledgeBases: number
    uploads: number
  }
}

export default function UserManagement() {
  const [users, setUsers] = useState<User[]>([])
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedRole, setSelectedRole] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [isLoading, setIsLoading] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const roles = ['all', 'ADMIN', 'EDITOR', 'VIEWER']
  const statuses = ['all', 'ACTIVE', 'INACTIVE', 'BANNED']

  // 获取用户列表
  const fetchUsers = async () => {
    try {
      setIsLoading(true)
      const response = await usersAPI.getUsers()
      setUsers((response.users || []) as User[])
    } catch (error: any) {
      console.error('Failed to fetch users:', error)
      toast.error(error.message || '获取用户列表失败')
    } finally {
      setIsLoading(false)
    }
  }

  // 更新用户状态
  const updateUserStatus = async (userId: string, status: 'ACTIVE' | 'INACTIVE' | 'BANNED') => {
    try {
      setIsSubmitting(true)
      await usersAPI.updateUser(userId, { status })
      toast.success('用户状态更新成功')
      fetchUsers() // 重新获取用户列表
    } catch (error: any) {
      console.error('Failed to update user status:', error)
      toast.error(error.message || '更新用户状态失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 删除用户
  const deleteUser = async (userId: string) => {
    if (!confirm('确定要删除这个用户吗？此操作不可撤销。')) {
      return
    }

    try {
      setIsSubmitting(true)
      await usersAPI.deleteUser(userId)
      toast.success('用户删除成功')
      fetchUsers() // 重新获取用户列表
    } catch (error: any) {
      console.error('Failed to delete user:', error)
      toast.error(error.message || '删除用户失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  // 初始化加载
  useEffect(() => {
    fetchUsers()
  }, [])

  const filteredUsers = users.filter(user => {
    const matchesSearch = user.username.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesRole = selectedRole === 'all' || user.role === selectedRole
    const matchesStatus = selectedStatus === 'all' || user.status === selectedStatus
    
    return matchesSearch && matchesRole && matchesStatus
  })

  const getRoleBadge = (role: string) => {
    switch (role) {
      case 'ADMIN':
        return <Badge variant="default" className="bg-red-100 text-red-800">管理员</Badge>
      case 'EDITOR':
        return <Badge variant="default" className="bg-blue-100 text-blue-800">编辑者</Badge>
      case 'VIEWER':
        return <Badge variant="secondary">普通用户</Badge>
      default:
        return <Badge variant="outline">{role}</Badge>
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'ACTIVE':
        return <Badge variant="default" className="bg-green-100 text-green-800">活跃</Badge>
      case 'INACTIVE':
        return <Badge variant="secondary">非活跃</Badge>
      case 'BANNED':
        return <Badge variant="outline" className="text-red-600 border-red-600">已暂停</Badge>
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  const getInitials = (name: string) => {
    return name.split('').slice(0, 2).join('')
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex items-center space-x-2">
          <Loader2 className="h-6 w-6 animate-spin" />
          <span>加载用户数据中...</span>
        </div>
      </div>
    )
  }

  return (
    <CompactLayout spacing="md" padding="md">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <CompactHeading>用户管理</CompactHeading>
          <CompactSubheading>管理系统用户和权限</CompactSubheading>
        </div>
        <AddUserDialog onUserAdded={fetchUsers} />
      </div>

      {/* 搜索和筛选 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">搜索和筛选</h3>
        </div>
        <div className="space-y-3">
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索用户名或邮箱..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="pl-8 h-8"
                />
              </div>
            </div>
            <div className="flex gap-2">
              <select
                value={selectedRole}
                onChange={(e) => setSelectedRole(e.target.value)}
                className="px-3 py-2 border border-input rounded-md bg-background text-sm h-8"
              >
                {roles.map(role => (
                  <option key={role} value={role}>
                    {role === 'all' ? '全部角色' : 
                     role === 'ADMIN' ? '管理员' :
                     role === 'EDITOR' ? '编辑者' : '普通用户'}
                  </option>
                ))}
              </select>
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value)}
                className="px-3 py-2 border border-input rounded-md bg-background text-sm h-8"
              >
                {statuses.map(status => (
                  <option key={status} value={status}>
                    {status === 'all' ? '全部状态' : 
                     status === 'ACTIVE' ? '活跃' :
                     status === 'INACTIVE' ? '非活跃' : '已暂停'}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </CompactCard>

      {/* 用户统计 */}
      <CompactGrid cols={4}>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <UserCheck className="h-4 w-4 text-green-600" />
            <div>
              <p className="text-xs text-muted-foreground">活跃用户</p>
              <p className="text-xl font-bold">{users.filter(u => u.status === 'ACTIVE').length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <UserX className="h-4 w-4 text-red-600" />
            <div>
              <p className="text-xs text-muted-foreground">非活跃用户</p>
              <p className="text-xl font-bold">{users.filter(u => u.status === 'INACTIVE').length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Mail className="h-4 w-4 text-blue-600" />
            <div>
              <p className="text-xs text-muted-foreground">总用户数</p>
              <p className="text-xl font-bold">{users.length}</p>
            </div>
          </div>
        </CompactCard>
        <CompactCard>
          <div className="flex items-center space-x-2">
            <Phone className="h-4 w-4 text-purple-600" />
            <div>
              <p className="text-xs text-muted-foreground">今日登录</p>
              <p className="text-xl font-bold">
                {users.filter(u => {
                  if (!u.lastLoginAt) return false
                  const today = new Date().toDateString()
                  const lastLogin = new Date(u.lastLoginAt).toDateString()
                  return today === lastLogin
                }).length}
              </p>
            </div>
          </div>
        </CompactCard>
      </CompactGrid>

      {/* 用户列表 */}
      <CompactCard>
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-lg font-semibold">用户列表 ({filteredUsers.length})</h3>
        </div>
        {filteredUsers.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            暂无用户数据
          </div>
        ) : (
          <div className="space-y-3">
            {filteredUsers.map((user) => (
              <div
                key={user.id}
                className="flex items-center justify-between p-3 border border-border rounded-lg hover:bg-accent/50 transition-colors"
              >
                <div className="flex items-center space-x-3">
                  <Avatar className="h-10 w-10">
                    <AvatarImage src={user.avatar} alt={user.username} />
                    <AvatarFallback>{getInitials(user.username)}</AvatarFallback>
                  </Avatar>
                  <div>
                    <div className="flex items-center space-x-2">
                      <h3 className="text-base font-medium">{user.username}</h3>
                      {getRoleBadge(user.role)}
                      {getStatusBadge(user.status)}
                    </div>
                    <div className="flex items-center space-x-3 mt-1 text-xs text-muted-foreground">
                      <span className="flex items-center space-x-1">
                        <Mail className="h-3 w-3" />
                        <span>{user.email}</span>
                      </span>
                      <span>注册时间: {new Date(user.createdAt).toLocaleDateString()}</span>
                      {user.lastLoginAt && (
                        <span>最后登录: {new Date(user.lastLoginAt).toLocaleString()}</span>
                      )}
                    </div>
                    <div className="flex items-center space-x-3 mt-1 text-xs text-muted-foreground">
                      <span>知识库数: {user._count.knowledgeBases || 0}</span>
                      <span>上传文件数: {user._count.uploads || 0}</span>
                    </div>
                  </div>
                </div>
                
                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <Button variant="ghost" size="icon" className="h-8 w-8">
                      <MoreHorizontal className="h-4 w-4" />
                    </Button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent align="end">
                    <DropdownMenuItem>
                      <Edit className="h-4 w-4 mr-2" />
                      编辑用户
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      onClick={() => updateUserStatus(
                        user.id, 
                        user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'
                      )}
                      disabled={isSubmitting}
                    >
                      <UserCheck className="h-4 w-4 mr-2" />
                      {user.status === 'ACTIVE' ? '暂停用户' : '激活用户'}
                    </DropdownMenuItem>
                    <DropdownMenuItem 
                      className="text-destructive"
                      onClick={() => deleteUser(user.id)}
                      disabled={isSubmitting}
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      删除用户
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            ))}
          </div>
        )}
      </CompactCard>
    </CompactLayout>
  )
}
